package org.example.controller;

import lombok.extern.slf4j.Slf4j;
import org.example.pojo.*;
import org.example.service.ClazzService;
import org.example.service.StudentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@Slf4j
public class ClazzController {
    @Autowired
    private ClazzService clazzService;
    @Autowired
    private StudentService studentService;

    /**
     * 查询所有班级信息
     * @return
     */
    @GetMapping("/clazzs/list")
    public Result list() {
        log.info("查询所有班级信息");
        List<Clazz> clazzList=clazzService.findAll();
        return Result.success(clazzList);
    }


    /**
     * 分页查询
     * @param clazzQueryParam
     * @return
     */
    @GetMapping("/clazzs")
    public Result page(ClazzQueryParam clazzQueryParam) {
        log.info("分页查询,参数:{}", clazzQueryParam);
        PageResult pageResult =clazzService.pageQuery(clazzQueryParam);
        return Result.success(pageResult);
    }

    /**
     * 根据id删除班级
     * @param id
     * @return
     */
    @DeleteMapping("/clazzs/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("根据id删除班级,id:{}", id);
        List<Student> studentList=studentService.selectByClazzId(id);
        if (studentList.size() > 0 && studentList != null) {
            throw new RuntimeException("对不起，当前班级下有学生，不能直接删除！");
        } else {
            clazzService.deleteById(id);
        }
        return Result.success();
    }

    /**
     * 根据id查询班级
     * @param id
     * @return
     */
    @GetMapping("/clazzs/{id}")
    public Result findById(@PathVariable Integer id){
        log.info("根据id查询班级,id:{}", id);
        Clazz clazz=clazzService.selectById(id);
        return Result.success(clazz);
    }

    /**
     * 修改班级信息
     * @param clazz
     * @return
     */
    @PutMapping("/clazzs")
    public Result update(@RequestBody Clazz clazz) {
        log.info("修改班级信息,clazz:{}", clazz);
        clazzService.update(clazz);
        return Result.success();
    }

    /**
     * 添加班级
     * @param clazz
     * @return
     */
    @PostMapping("/clazzs")
    public Result add(@RequestBody Clazz clazz) {
        log.info("添加班级,clazz:{}", clazz);
        clazzService.insert(clazz);
        return Result.success();
    }
}
